package adminSys

import (
	"github.com/gofiber/fiber/v2"
	"github.com/mojocn/base64Captcha"
)

type SysAdminController struct {
	BaseSysController
}

// 定义全局变量来存储验证码对象
var captchaStore = base64Captcha.DefaultMemStore

// GenerateCaptcha 生成验证码并返回其ID和Base64编码的图片
func GenerateCaptcha(c *fiber.Ctx) error {
	captchaId, captchaImage, err := generateCaptcha()
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": "Failed to generate captcha",
		})
	}
	return c.JSON(fiber.Map{
		"captchaId":    captchaId,
		"captchaImage": captchaImage,
	})
}

// generateCaptcha 生成验证码并返回其ID和Base64编码的图片
func generateCaptcha() (string, string, error) {
	driver := base64Captcha.NewDriverDigit(70, 240, 5, 0.7, 80)
	captcha := base64Captcha.NewCaptcha(driver, captchaStore)
	return captcha.Generate()
}
func GetCaptcha(c *fiber.Ctx) error {
	captchaId, captchaImage, err := generateCaptcha()
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).SendString("Failed to generate captcha")
	}
	return c.JSON(fiber.Map{
		"captchaId":    captchaId,
		"captchaImage": captchaImage,
	})
}

// Login 渲染登录页面并生成验证码
func Login(c *fiber.Ctx) error {

	return c.Render("sys_login", fiber.Map{
		"title": "用户登录",
	})
}

func (uc *SysAdminController) LoginServer(c *fiber.Ctx) error {
	username := c.Query("username")
	password := c.Query("password")
	captchaId := c.Query("captchaId")
	captchaValue := c.Query("captchaValue")

	if captchaId == "" || password == "" || username == "" || captchaValue == "" {
		return uc.returnSuccess(c, fiber.StatusUnauthorized, "用户名、密码、验证码不能为空！", "")
	}
	// 验证验证码
	if !captchaStore.Verify(captchaId, captchaValue, true) {
		return uc.returnError(c, fiber.StatusCreated, "验证码已过期或错误！")
	}
	return uc.returnSuccess(c, fiber.StatusOK, "登录成功！", "")
}

func Logout() {

}

func Home(c *fiber.Ctx) error {
	return c.Render("sys_index", fiber.Map{
		"hello": "2222",
	})
}
func Main(c *fiber.Ctx) error {
	return c.Render("sys_main", fiber.Map{
		"hello": "world",
	})
}
